var User = function () {

    var basePath = ROOT_PATH + 'upms/user/',
        pagePath = ROOT_PATH + 'pages/upms/user/',
        $dataGrid = null,
        $resourceGrid = null,
        $deptTree = null,
        $roleGrid = null,
        $dialog = null;

    function initGrid(gridId) {
        var gid = gridId || '#grid-data';
        $dataGrid = BsGridUtil.initBsGrid({
            gridId: gid,
            url: basePath + "list",
            toolbar:"#userTb",
            singleSelect:false,
            rowStyle: function (value, row, index) {
                if (value.status && value.status.code == 1) {
                    return {css: {"color": "red"}}
                } else {
                    return value;
                }
            },
            columns: [
                {field: 'selectItem', checkbox:true},
                {field: 'userId', title: 'Id',sortable: true},
                {field: 'userName', title: '用户名'},
                {field: 'realName', title: '真实姓名'},
                {field: 'deptName', title: '所在部门'},
                {field: 'status', title: '状态',formatter: FormUtils.enumFormatter},
                {field: 'phone', title: '手机号码'},
                {field: 'createTime', title: '创建时间'},
                {field: 'gender', title: '性别', formatter: FormUtils.enumFormatter},
                {
                    field: 'optFormatter', title: '操作',
                    formatter: function (column, row) {
                        if ($('#setRoleUser').length > 0 && $('#updateUserPassword').length > 0) {
                            return '<a href="javascript:User.editUser(' + row.userId + ')" class="btn btn-xs btn-primary"><span class="fa fa-repeat"></span>编辑</a>' + "&nbsp;" +
                                '<a href="javascript:User.assignRole(' + row.userId + ')" class="btn btn-xs btn-primary"><span class="fa fa-hand-o-right"></span>设置角色</a>';
                        } else if ($('#setRoleUser').length == 0 && $('#updateUserPassword').length > 0) {
                            return '<a href="javascript:User.editUser(' + row.userId + ')" class="btn btn-xs btn-primary"><span class="fa fa-repeat"></span>编辑</a>';
                        } else if ($('#setRoleUser').length > 0 && $('#updateUserPassword').length == 0) {
                            return '<a href="javascript:User.assignRole(' + row.userId + ')" class="btn btn-xs btn-primary"><span class="fa fa-hand-o-right"></span>设置角色</a>';
                        } else {
                            return null;
                        }
                    }
                }
            ],
        });
        return $dataGrid;
    }

    /**
     * 编辑
     */
    function editUser(id) {
        $.closeTabWithTitle("编辑用户");
        $.createTabWithParam("upms/user/goEdit","编辑用户");
        $.Get(basePath + 'get', {id: id}, function (data) {
            $.iframeOnload(function () {
                if (data) {
                    var $target = $.getTabWithTitle("编辑用户");
                    var $form = $($target).find("#userEditForm");
                    FormUtils.setValues($form, data.data);
                    bindInitDeptEvent($form);
                    bindInitRoleEvent($form);
                    bindInitResourceEvent($form);
                    validateUser($form);
                    //基本初始化
                    $($form).find('#sw-content input').switchBtn("initBtn");
                    //点击触发事件，监听按钮状态
                    $($form).find('#sw-content input').on('switchChange.bootstrapSwitch',function(event,state){
                        //获取状态
                        if (state){
                            $($form).find("#status").val(0);
                        }else{
                            $($form).find("#status").val(1);
                            //手动设置按钮状态
                            $($form).find('#sw-content input').bootstrapSwitch('state',false);
                        }
                    });
                    //手动设置按钮状态
                    $($form).find('#sw-content input').val(data.data.status.code);
                    if(data.data.status.code == 1){
                        //手动设置按钮状态
                        $($form).find('#sw-content input').switchBtn('setState',false);
                    }else{
                        $($form).find('#sw-content input').switchBtn('setState',true);
                    }
                }  else{
                    Dialog.danger("用户信息不存在");
                }
            })
        })
    }

    //指派角色
    function assignRole(userId) {
        var roleIds = [];

        //打开获用户拥有的角色列表modal框
        $.Get(basePath + 'getAllRoles', function (page) {
            $dialog = $(page);
            var $form = $dialog.find('form:first');
            $dialog.modal().on("hidden.bs.modal", function () {
                $dialog.remove();
            });
            $.Get(basePath + 'getRolesOfUser', {userId: userId}, function (data) {
                if (data) {
                    var roleIds = data.data;
                    $.each(roleIds, function (i, roleId) {

                        //选中用户已拥有的角色
                        $form.find("input[value=" + roleId + "]").attr("checked", true);
                    })
                } else {
                    Dialog.error("用户角色不存在");
                }
            });

            //提交角色id
            $dialog.find('#submitBtn').click(function () {
                $form.find('input[name="roleName"]:checked').each(function () {
                    if ($(this).val() != null) {
                        roleIds.push($(this).val());
                    }
                });
                if (roleIds.length == 0){
                    Dialog.warning("请至少选择一个角色");
                    return;
                }
                $.Ajax({
                    url: basePath + "setRole",
                    data: {roleIds: roleIds, userId: userId},
                    container: $dialog,
                    success: function () {
                        $dialog.modal('hide');
                    }
                });
                return false;

            });
        })

    }


    /**
     * 创建user
     */
    function createUser() {
        $.createTabWithParam("upms/user/create","添加用户");
    }

    /**
     * 初始话岗位选择列表
     */
    function bindInitPostEvent(deptId,$form) {
        var postSelect = $form.find("#post");
        postSelect.empty();
        var option = "<option value='-1'>请选择</option>";
        //获取所有岗位
        $.Get(ROOT_PATH + "upms/post/findPostByDept",{deptId:deptId},function (data) {
            for (var i = 0; i < data.length; i++) {
                var postId = $($form).find("input[name='postIds']").val();
                if (postId && postId == data[i].id){
                    option += "<option selected='selected' value='"+ data[i].id + "'>"+ data[i].postName +"</option>"
                }else{
                    option += "<option value='"+ data[i].id + "'>"+ data[i].postName +"</option>"
                }
            }
            postSelect.append(option);
            $(postSelect).chosen();
        })

        postSelect.change(function () {
            var postId = $(this).val();
            $form.find("input[name='postIds']").val(postId == -1? "": postId);
        })
    }


    /**
     * 绑定初始化资源grid事件
     * @param $form
     */
    function bindInitResourceEvent($form) {
        $resourceGrid = BsGridUtil.initBsTreeGrid({
            url: ROOT_PATH + "upms/resource/list",
            gridId: $form.find("#resourceGrid"),
            toolbar: "",
            showRefresh: false,
            treeColumn: 1,
            columns: [
                {field: "btSelectItem", checkbox: true},
                {field: 'id', title: "Id", visible: false},
                {field: 'name', title: "名称"},
                {
                    field: 'status',
                    title: '状态',
                    formatter: FormUtils.enumFormatter,
                    cellStyle: function (value, row, index) {
                        if (value && value.code == 2) {
                            return {css: {"color": "red"}}
                        } else {
                            return {css: {"color": "blue"}}
                        }
                    }
                },
            ],
            onLoadSuccess:function () {
                // $($resourceGrid).find("input[type='checkbox']").attr("disabled",true);
            }
        });
    }

    /**
     * 初始化组织机构
     * @param $form form表单
     * @param deptIds 已选择的机构
     */
    function bindInitDeptEvent($form) {
        var deptTree = $form.find("#deptTree");
        $deptTree = Organization.initTree(deptTree);

        //初始话部门下面的岗位
        $deptTree.setting.callback.onClick = function (event, treeId, treeNode) {
            var ids = treeNode.id.split("-");

            //1组织2部门3岗位
            var type = parseInt(ids[0]);
            //对应id
            var id = ids[1];

            //选择的是部门
            if (type === 2) {
                //初始化岗位下拉
                bindInitPostEvent(id,$form);
                $form.find("input[name='deptIds']").val(id);
            }else{
                //清除部门id
                $form.find("input[name='deptIds']").val("");
            }
        },
        $deptTree.setting.callback.onAsyncSuccess = function (event, treeId, treeNode,nodes) {
            var deptId = $($form).find("input[name='deptIds']").val();
            //默认展开节点
            $deptTree.expandAll(true);
            //节点
            if (nodes.length > 0) {
                for(var i = 0;i < nodes.length;i++){
                    var nodeElement = nodes[i].id.split("-");
                    //部门类型
                    if (nodeElement[0] == 2) {
                        //选中部门
                        if (deptId == nodeElement[1]) {
                            var node = $deptTree.getNodeByParam("id", (nodes[i].id));
                            $deptTree.selectNode(node);
                            //同时初始化岗位
                            bindInitPostEvent(deptId,$form);
                        }
                    }
                }
            }
        }
    }

    /**
     * 展示资源
     * @param resourceIds
     */
    function showResource(roleIds) {
        //查询角色所拥有的权限
        $.Ajax({
            url: basePath + "findResourceIdsByRoleAndPost",
            container: $resourceGrid,
            data: {
                // postIds: postIds,
                roleIds: roleIds
            },
            success: function (data) {
                //根据资源id选中对应的数据
                if (data.length > 0) {
                    $resourceGrid.bootstrapTable("checkBy", {field: "id", values: data});
                    $resourceGrid.find("input[type='checkbox']").attr("disabled", true);
                }else{
                    $resourceGrid.bootstrapTable("refresh");
                }
            }
        });
    }

    /**
     * 获取选中的角色
     */
    function getSelectedRoleIds() {
        var roleNodes = $roleGrid.bootstrapTable('getSelections');
        var roleIds = [];
        if (roleNodes.length > 0) {
            $.each(roleNodes, function () {
                roleIds.push(this.id);
            })
        }
        return roleIds;
    }

    /**
     * 获取已选择的岗位节点
     * @returns
     */
    function getSelectedPostIds() {
        var nodes = $postGrid.bootstrapTable('getSelections');
        var postIds = [];
        if (nodes.length > 0) {
            var node = nodes[0].id.split("-");
            var url = "";
            //组织
            if (node[0] == 1) {
                url = ROOT_PATH + "permission/organization/get";
            } else if (node[0] == 2) {
                //部门
                url = ROOT_PATH + "permission/department/get";
            } else if (node[0] == 3) {
                url = ROOT_PATH + "permission/post/get";
                $.Get(url, {id: node[1]}, function (data) {
                    if (data.data && data.data.type.code == 3) {
                        postIds.push(data.data.originId);
                    }
                })
            }
        }
        return postIds;
    }

    /**
     * 初始化角色
     * @param $form form表单
     * @param roleIds 已选择的角色
     */
    function bindInitRoleEvent($form) {
        var $roleId = $form.find('#roleGrid');
        $roleGrid = Role.initGrid4Choose($roleId, {
            onCheck: function (row) {
                var roleIds = getSelectedRoleIds();
                $form.find('input[name="roleIds"]').val(roleIds);
                showResource(roleIds);
            },
            onCheckAll: function (row) {
                var roleIds = getSelectedRoleIds();
                $form.find('input[name="roleIds"]').val(roleIds);
                showResource(roleIds);
            },
            onUncheck: function (row) {
                var roleIds = getSelectedRoleIds();
                $form.find('input[name="roleIds"]').val(roleIds);
                showResource();
            },
            onUncheckAll: function () {
                var roleIds = getSelectedRoleIds();
                $form.find('input[name="roleIds"]').val(roleIds);
                showResource();
            },
            onLoadSuccess: function () {
                var $roleIds = [];
                var roleIds = $form.find('input[name="roleIds"]').val();
                var dataIntArr = roleIds.split(",");
                for (var i = 0; i < dataIntArr.length; i++) {
                    $roleIds.push(parseInt(dataIntArr[i]));
                }
                if ($roleIds.length > 0) {
                    $roleGrid.bootstrapTable("checkBy", {field: "id", values: $roleIds});
                }
            },
        });
    }


    function validateUser(formId) {
        var $form = $(formId);
        FormUtils.validate($form, {
            rules: {
                userName:{
                    maxlength: 15,
                    minlength: 2,
                    required: true
                },
                realName: {
                    maxlength: 15,
                    minlength: 2,
                    required: true
                },
                phone:{
                    maxlength: 11,
                    minlength: 11,
                },
                remark:{
                    maxlength: 200,
                }
            },
            message:{
                userName:{
                    required:  "请输入用户名",
                    maxlength: "最多允许输入15个字符",
                    minlength: "最少输入2个字符"
                },
                realName: {
                    required:  "请输入真实姓名",
                    maxlength: "最多允许输入15个字符",
                    minlength: "最少输入2个字符"
                },
                remark:{
                    maxlength:"最多允许输入200个字符" ,
                },
                phone:{
                    maxlength: "最多允许输入11个字符",
                    minlength: "最少输入11个字符"
                },
            },
            submitHandler: function (form) {
                var formObj = FormUtils.getFormObj(form);
                if (formObj.deptIds == undefined) {
                    window.parent.Dialog.warning("请选择部门");
                    return;
                }else if (formObj.roleIds == undefined){
                    Dialog.warning("请选择角色");
                    return;
                }
                formObj.status = $(form).find("#status").val();
                $.Ajax({
                    url: $($form).attr("action"),
                    data: formObj,
                    container: $form,
                    success: function (r) {
                        $.activeTabWithTitle('用户管理');
                        Dialog.success(r);
                    },
                });
            }
        })
    }

    /**
     * 批量解冻和冻结
     * @param statusNumber
     * @param gridId
     */
    function setSatus(statusNumber, gridId) {
        var userIds = [];
        var selectUsers = $dataGrid.bootstrapTable("getSelections");

        if (selectUsers.length > 0) {
            for (var i = 0; i < selectUsers.length; i++) {
                userIds.push(selectUsers[i].userId);
            }

            if (statusNumber == 1){
                Dialog.prompt("请输入冻结理由",function (r) {
                    if (r.length == 0){
                        Dialog.warning("最少输入1个字符")
                        return;
                    }else if (r.length > 50){
                        Dialog.warning("最多允许输入50个字符");
                        return;
                    }
                    if (r){
                        updateStatus(r);
                    }else{
                        Dialog.warning("操作已取消");
                    }
                })
            }else{
                updateStatus();
            }
        } else {
            Dialog.warning('请选择用户');
        }

        function updateStatus(r) {
            $.Ajax({
                url: basePath + "updateStatus",
                data: {userIds: userIds, statusNumber: statusNumber,disableReason:r},
                success: function (msg) {
                    Dialog.success(msg);
                    $dataGrid.bootstrapTable("refresh");
                }
            });
        }

    }

    /**
     * 查看详情
     * @param id
     */
    function getInfo(id) {
        $.Get(pagePath + 'user-info.html', function (page) {
            $dialog = $(page);
            var $form = $dialog.find('form:first');
            $dialog.modal();
            $.Get(basePath + 'get', {id: id}, function (data) {
                if (data) {
                    FormUtils.setValues($form, data.data);
                } else {
                    Dialog.error("用户信息不存在");
                }
            });
        })
    }

    function validatePassword(formId) {
        var $form = $(formId);
        FormUtils.validate($form, {}, function () {
            $.Ajax({
                url: $($form).attr("action"),
                data: FormUtils.getFormObj($form),
                method: "post",
                container: $form,
                success: function (r) {
                    $dialog.modal('hide');
                    Dialog.success('操作成功');
                    $dataGrid.bootstrapTable('refresh');
                }
            });
        });
    }

    /**
     * 删除角色
     */
    function deleteUser() {
        var selected = $dataGrid.bootstrapTable("getSelections");
        var ids = [];
        if (selected.length > 0){
            for (var i = 0; i < selected.length; i++) {
                ids.push(selected[i].userId);
            }
            $.Post(basePath + "delUser",{userIds:ids},function (data) {
                $dataGrid.bootstrapTable("refresh");
                Dialog.success(data.data);
            })
        } else{
            Dialog.warning("请选择用户");
        }
    }
    return {
        initGrid: initGrid,
        deleteUser:deleteUser,
        createUser: createUser,
        editUser: editUser,
        getInfo: getInfo,
        assignRole: assignRole,
        setSatus: setSatus,
        validatePassword: validatePassword,
        bindInitPostEvent:bindInitPostEvent,
        bindInitDeptEvent:bindInitDeptEvent,
        bindInitRoleEvent:bindInitRoleEvent,
        bindInitResourceEvent:bindInitResourceEvent,
        validateUser:validateUser
    }
}();